﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Mvc;

namespace NuGet.Enterprise.Server.Infrastructure
{
    public class RedirectHttpHandler 
        : IHttpHandler
    {
        public RedirectHttpHandler(RequestContext context, string targetUrl)
            : this(context, targetUrl, false)
        { }

        public RedirectHttpHandler(RequestContext context, string targetUrl, bool permanent)
        {
            TargetUrl = targetUrl;
            Permanent = permanent;

            if (TargetUrl.StartsWith("~/"))
            {
                string virtualPath = TargetUrl.Substring(2);

                Route route = new Route(virtualPath, null);

                var vpd = route.GetVirtualPath(context, context.RouteData.Values);

                if (vpd != null)
                {
                    TargetUrl = "~/" + vpd.VirtualPath;
                }
            }
        }

        public bool Permanent { get; private set; }

        public string TargetUrl { get; private set; }

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            if (this.Permanent)
            {
                context.Response.Status = "301 Moved Permanently";
                context.Response.StatusCode = 301;
                context.Response.AddHeader("Location", TargetUrl);
            }
            else
            {
                context.Response.Redirect(TargetUrl, false);
            }
        }
    }
}